package top.biangege.bbs.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import top.biangege.bbs.aop.annotation.RedisCache;
import top.biangege.bbs.entity.Result;
import top.biangege.bbs.entity.Video;
import top.biangege.bbs.entity.VideoClass;
import top.biangege.bbs.entity.VideoItem;
import top.biangege.bbs.mapper.VideoItemMapper;
import top.biangege.bbs.mapper.VideoMapper;
import top.biangege.bbs.service.VideoService;
import top.biangege.bbs.utils.HttpUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class VideoServiceImpl extends ServiceImpl<VideoMapper, Video> implements VideoService {

    @Resource
    private VideoMapper videoMapper;

    @Resource
    private VideoItemMapper videoItemMapper;

    @Override
    @RedisCache(duration = 60)
    public Result getIndexData() {

        List<VideoClass> videoClassList = videoMapper.selectVideoClass();
        for (VideoClass videoClass : videoClassList) {
            List<Video> videos = videoMapper.selectList(new QueryWrapper<Video>().eq("type_id", videoClass.getType_id()).orderByDesc("vod_time").last("limit 10"));
            for (Video video : videos) {
                VideoItem videoItem = videoItemMapper.selectById(video.getVod_id());
                if (videoItem == null) {
                    String s = HttpUtils.doGet("https://taopianapi.com/home/cjapi/as/mc10/vod/json?ac=videolist&t=&pg=&h=&ids=" + video.getVod_id());
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    List<VideoItem> list = jsonObject.getJSONArray("list").toJavaList(VideoItem.class);
                    videoItemMapper.insert(list.get(0));
                    video.setVideoItem(list.get(0));
                } else {
                    video.setVideoItem(videoItem);
                }
            }

            videoClass.setVideoList(videos);
        }


        return Result.success(videoClassList);
    }
}
